<?php
class HomeController extends MController {
    const SETUP_STARTED = 'started';
    const SETUP_FINISHED = 'finished';

    public function indexAction(){
        if ($this->getRequest()->isAjax()){
            MSession::getInstance()->setValue('mlSetup', self::SETUP_STARTED);
            $this->renderPartial();
        } else {
            $this->render();
        }
    }
    
    public function setupAction(){
        if ($this->getRequest()->isAjax()){
            $languages = array();
            if ($handle = opendir(MD_LIB.DS.'messages')){
                while (false !== ($file = readdir($handle))) {
                    $extension = pathinfo($file, PATHINFO_EXTENSION);
                    if ($extension == 'php')
                        array_push($languages, basename($file, '.php'));
                }
            }
            $this->renderPartial('setup', array('languages'=>$languages));
        } else {
            MRequest::redirect('?r=ml-setup');
        }
    }
    
    public function manualAction(){
        if ($this->getRequest()->isAjax()){
            $this->renderPartial();
        } else {
            MRequest::redirect('?r=ml-setup');
        }
    }
    
    public function finalizeAction(){
        if ($this->getRequest()->isPost()){
            $dirWritable = is_writable(MD_CONF);
            
            $post = $this->getRequest()->getPost();
            $configContent = file_get_contents(MD_CONF.DS.'config.sample.php');
            $configContent = str_ireplace('{{mandrill-title}}', $post['name'], $configContent);
            $configContent = str_ireplace('{{mandrill-defaultLanguage}}', $post['language'], $configContent);
            $configContent = str_ireplace('{{mandrill-baseUrl}}', $post['baseUrl'], $configContent);
            $connectionString = 'mysql://'.$post['databaseLogin'].((!empty($post['databasePassword'])) ? ':'.$post['databasePassword'] : NULL).'@'.$post['databaseHost'].'/'.$post['databaseName'];
            $configContent = str_ireplace('{{mandrill-dbConnection}}', $connectionString, $configContent);
            
            if ($dirWritable){
                if ($handle = fopen(MD_CONF_FILE, 'w')){
                    fwrite($handle, $configContent);
                    fclose($handle);
                }
            }
            
            $this->render('finalize', array('dirWritable'=>$dirWritable, 'configContent'=>$configContent));
        } else {
            MRequest::redirect('?r=ml-setup');
        }
    }
    
    public function testConnectionAction(){
        if ($this->getRequest()->isAjax()){
            if (file_exists(MD_CONF_FILE)){
                $confArray = require (MD_CONF_FILE);
                Mandrill::getApp()->dbConnection = $confArray['dbConnection'];

                ActiveRecord\Config::initialize(function($cfg){
                    $cfg->set_model_directory(__DIR__.DS.'..'.DS.'models');
                    $cfg->set_connections(Mandrill::getApp()->dbConnection);
                    $cfg->set_default_connection('mandrill');
                });

                try {
                    $result = ActiveRecord\Connection::instance()->query('SELECT 1;');
                    if ($result != NULL)
                        $result = __tag('p', array('class'=>'success'), __t('mandrill.setup.successConnection'));
                    else
                        $result = __tag('p', array('class'=>'error'), __t('mandrill.setup.errorConnection'));
                } catch (Exception $exc) {
                    $result = __tag('p', array('class'=>'error'), __t('mandrill.setup.errorConnection'));
                }
            } else {
                $result = __tag('p', array('class'=>'error'), __t('mandrill.setup.confFileNotExists'));
            }
            $this->renderPartial('testConnection', array('result'=>$result));
        } else {
            MRequest::redirect('?r=ml-setup');
        }
    }
    
    public function dbConfigurationAction(){
        if ($this->getRequest()->isAjax()){
            if (file_exists(MD_CONF_FILE)){
                $confArray = require (MD_CONF_FILE);
                Mandrill::getApp()->dbConnection = $confArray['dbConnection'];

                ActiveRecord\Config::initialize(function($cfg){
                    $cfg->set_model_directory(__DIR__.DS.'..'.DS.'models');
                    $cfg->set_connections(Mandrill::getApp()->dbConnection);
                    $cfg->set_default_connection('mandrill');
                });
                
                $dbName = ActiveRecord\Connection::parse_connection_url(ActiveRecord\Config::instance()->get_connection('mandrill'))->db;
                $requetes = '';
                $sql = file(__DIR__.DS.'..'.DS.'install'.DS.'create_base.sql');
                foreach ($sql as $l){
                    if (substr(trim($l),0,2)!="--"){
                        $requetes .= str_ireplace('{{dbname}}', $dbName, $l);
                    }
                }
                $reqs = explode(';', trim($requetes));

                try {
                    foreach ($reqs as $requete){
                        if (isset($requete) && !empty($requete)){
                            ActiveRecord\Connection::instance()->query($requete.';');
                        }
                    }
                    $result = __tag('p', array('class'=>'success'), __t('mandrill.setup.successConfiguration'));
                    $result .= __tag('br');
                    $result .= __tag('a', array('class'=>'button ajax', 'href'=>'?r=ml-setup/home/userCreation'), __t('mandrill.setup.lastStep'));
                } catch (Exception $exc) {
                    $result = __tag('p', array('class'=>'error'), __t('mandrill.setup.errorConfiguration'));
                }
            } else {
                $result = __tag('p', array('class'=>'error'), __t('mandrill.setup.confFileNotExists'));
            }
            $this->renderPartial('dbConfiguration', array('result'=>$result));
        } else {
            MRequest::redirect('?r=ml-setup');
        }
    }
    
    public function userCreationAction(){
        if ($this->getRequest()->isPost()){
            $post = $this->getRequest()->getPost();
            if (isset($post['login']) && isset ($post['display_name']) && isset ($post['password']) && isset ($post['email'])){
                $confArray = require (MD_CONF_FILE);
                Mandrill::getApp()->dbConnection = $confArray['dbConnection'];

                ActiveRecord\Config::initialize(function($cfg){
                    $cfg->set_model_directory(__DIR__.DS.'..'.DS.'models');
                    $cfg->set_connections(Mandrill::getApp()->dbConnection);
                    $cfg->set_default_connection('mandrill');
                });
                
                $user = new User();
                $user->set_attributes($post);
                $user->creation_date = new DateTime();
                $user->status = 1;
                $user->super_admin = 1;
                $user->save();
                MSession::getInstance()->setValue('mlSetup', self::SETUP_FINISHED);
                MRequest::redirect('?r=ml-admin');
            } else {
                $this->render();
            }
        } else if ($this->getRequest()->isAjax()) {
            $this->renderPartial();
        } else {
            MRequest::redirect('?r=ml-setup');
        }
    }
}
?>
